<?php
/**
 * Core_Controller_Front
 * 
 * @author naspeh
 * @version $Id: Front.php 660 2008-06-16 09:41:40Z naspeh $
 */
class Core_Controller_Front extends Zend_Controller_Front
{
    /**
     * Возвращает экзепляр фронт-контроллера
     *
     * @return Core_Controller_Front
     */
    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance =  new self();
        }
        return self::$_instance;
    }
    /**
     * Стартует
     *
     * @return Core_Controller_Front
     */
    public function start($withDispatch = true)
    {
        $this->setModuleControllerDirectoryName(Core_Loader::SUFFIX_CONTROLLERS)
              ->setBaseUrl('')
              ->throwExceptions(false)
              ->returnResponse(true)
              ->registerPlugin(new Core_Controller_Plugin_HeadTitle())
              ->setDefaultModule(Core_Loader::MODULE_DEFAULT)
              ->addModuleDirectory(DIR_MODULES);
        if (Core_Db::getInstance()->getProfiler()->getEnabled()) {
            $this->registerPlugin(new Core_Controller_Plugin_DbProfiler());
        }
        
        $layout = Zend_Layout::startMvc(array());
        $view = $layout->getView();
        $view->setBasePath(Core_Loader::getModuleToPath(Core_Loader::MODULE_DEFAULT) . Core_Loader::SUFFIX_VIEWS, 'Core_View_');
        $layout->setView($view);
        $layout->setLayout('layout');
        
        $router = new Zend_Controller_Router_Rewrite();
        $router->removeDefaultRoutes();
        $router->addRoutes(Core_Config::get('routes'));
        $this->setRouter($router);
        
        if ($withDispatch) {
            $response = $this->dispatch();
            $response->setHeader('Content-Type', 'text/html; charset=utf-8');
            $response->sendResponse();
            if ($response->isException()) {
                $exceptions = $response->getException();
                foreach ($exceptions as $exception) {
                    if (in_array($exception->getCode(), array(403, 404))) {
                        Core_Log::debug($exception->__toString());
                    } else {
                        Core_Log::emerg($exception->__toString());
                    }
                }
            }
        }
        return $this;
    }
}